package io.renren.wechat.support;

import ch.qos.logback.core.PropertyDefinerBase;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * Copyright(c) 1995-2019 by Asiainfo.com(China)
 * All rights reserved.
 *
 * @author Jacob Liu <Liuxy8@asiainfo.com>
 * 2020/1/2 12:41
 */
public class LogHomeSetting extends PropertyDefinerBase {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogHomeSetting.class);
    private static final String LOG_HOME_ENV_VARIABLE = "ENTERPRISE_WECHAT_HOME";
    private static final String APP_STARTED_PATH = System.getProperty("user.dir");

    @Override
    public String getPropertyValue() {
        String appHomePath = System.getProperty(LOG_HOME_ENV_VARIABLE);
        LOGGER.info(">>>enterprise-wechat home: {}", appHomePath);
        LOGGER.info(">>>user.dir: {}", APP_STARTED_PATH);
        if (StringUtils.isNotBlank(appHomePath)) {
            String logPath = appHomePath + File.separator + "logs";

            LOGGER.info(">>>defined logback path: {}", logPath);
            return logPath;
        }

        return getDefaultLogPath();
    }

    private String getDefaultLogPath() {
        String path = APP_STARTED_PATH;
        if (path.endsWith("/bin")) {
            path = new File(path).getParentFile().getPath();
        }

        String logPath = path + File.separator + "logs";
        LOGGER.info(">>>default logback path: {}", logPath);

        return logPath;
    }
}
